<?php

namespace app\index\controller\baidu;

use app\common\model\PromotionGroup;
use app\index\service\OcpcService;
use ShidianUtil\Thinkphp\Response\ApiResponse;
use think\APP;
use think\exception\ValidateException;
use think\Request as Request;

/**
 * Ocpc 控制器
 * Class Ocpc
 * @package app\index\controller\baidu;
 * @link https://www.kancloud.cn/manual/thinkphp6_0/1037509
 */
class Ocpc
{
    // 请求参数
    private Request $request;
    private \baidu\Ocpc $ocpc;

    public function __construct(Request $request, \baidu\Ocpc $ocpc)
    {
        $this->request = $request;
        $this->ocpc = $ocpc;
    }

    /**
     * 百度回传
     * @return ApiResponse
     * @url /baidu/ocpc/save
     * @deprecated
     */
    public function save(): ApiResponse
    {
        $request = $this->request;

        $logidUrl = $request->param('logidUrl');
        $newType = $request->param('newType');
        $token = '';

        // 渠道链路
        ['pf' => $pf, 'chain' => $chain, 'promotionGroupId' => $promotionGroupId] = getChainParams();

        if (is_id($promotionGroupId)) {
            $promotionGroup = PromotionGroup::where('id', $promotionGroupId)->find();
            if ($promotionGroup) {
                $token = $promotionGroup->bdToken;
            }
        }

        if (is_blank($token)) {
            throw new ValidateException('缺少[token]');
        }

        if (is_blank($logidUrl)) {
            throw new ValidateException('缺少[logidUrl]');
        }

        if (is_blank($newType)) {
            throw new ValidateException('缺少[newType]');
        }

        $response = $this->ocpc->uploadConvertData($token, $logidUrl, $newType);

        if (!$response->isSuccess()) {
            throw new ValidateException('回传失败');
        }

        return ApiResponse::success(null);
    }

}
